#include "cv.h"
#include "highgui.h"
#include <iostream>
//Variables
using namespace std;
char wndname[] = "Edge";
char tbarname[] = "Threshold";
int edge_thresh = 1;

IplImage *frame =0, *cedge = 0, *gray = 0, *edge = 0;

void on_trackbar(int h)
{
    cvSmooth( gray, edge, CV_BLUR, 3, 3, 0, 0 );
    cvNot( gray, edge );

    // Run the edge detector on grayscale
    cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 3);//http://www.seas.upenn.edu/~bensapp/opencvdocs/ref/opencvref_cv.htm#cv_imgproc_features find:Canny
  
    cvZero( cedge );
    // copy edge points
    cvCopy( frame, cedge, edge );

    cvShowImage("Example2", cedge);
}


int main( int argc, char** argv ) {

	cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );
	CvCapture* capture;
	if(argc == 1){
		capture = cvCreateCameraCapture(-1);	
	}
	else{
		capture = cvCreateFileCapture(argv[1]);
	}
	//create slider bar
	cvCreateTrackbar(tbarname, "Example2", &edge_thresh, 100, on_trackbar);
	while(1) {
		frame = cvQueryFrame( capture );//loads video or image into gui frame	
		if (!frame){cout <<"Error reading file" ;break;}
		//display dimension of picture/video
		cedge = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 3);
		//printf("Frame Width: %d \nFrame Height: %d \n \n", frame->width,frame->height);
		// Convert to grayscale
		gray = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 1);
		edge = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 1);
		cvCvtColor(frame, gray, CV_BGR2GRAY);
		//show image
		on_trackbar(0);
		char c = cvWaitKey(33);					//33ms is an obvious difference from 200ms
		cvReleaseImage(&gray);
		cvReleaseImage(&edge);
		cvReleaseImage(&cedge);
		if (c == 27) break;
	}
	cvReleaseCapture( &capture );
	cvDestroyWindow( "Example2" );
}
